<?php
/**
 * Created by ghostsf
 * Date: 2016/4/21
 */

namespace app\admin\controller;

use app\admin\model\Course;
use app\admin\model\Grade;
use think\Db;
use think\Session;
/**
 * 成员管理
 * Class Course
 * @package app\admin\controller
 */
class ProjectController extends CommonController
{
    public function getCourseJSON()
    {
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        if($_POST['user_phone']!=''){
            $user_phone = $_POST['user_phone'];
            $where['u.user_phone|u.user_username'] = array('like',"%$user_phone%");
        }
        if($_POST['role']!=''){
            $where['team_member_role'] = $_POST['role'];
        }
        if($_POST['join_time']!=''){
            $where['team_member_join_time'] = array('EGT',$_POST['join_time']);
        }
        $where['team_id'] =session('loginSession')['team_id'];
        $where['team_member_remove'] = 2;
        $res = Db::table('up_team_members')->alias('a')
                                    ->where($where)
                                    ->join('up_u_user u','u.user_id=a.team_member_user_id','left')
                                    ->join('up_u_user uuu','uuu.user_id=a.team_member_up_user','left')
                                    ->field('a.*,u.user_username,u.user_phone,uuu.user_username as up_user')
                                    ->limit($rows * ($page - 1), $rows)
                                    ->select();
        $total = Db::table('up_team_members')->alias('a')
            ->where($where)
            ->join('up_u_user u','u.user_id=a.team_member_user_id','left')
            ->join('up_u_user uuu','uuu.user_id=a.team_member_up_user','left')
            ->count();
        $data['total'] = $total;
        $data['rows'] = $res;
        return json_encode($data);
    }

   /**
    * 导出下载
    */
   public function excelDownload(){
       if($_POST['user_phone']!=''){
           $user_phone = $_POST['user_phone'];
           $where['u.user_phone|u.user_username'] = array('like',"%$user_phone%");
       }
       if($_POST['role']!=''){
           $where['team_member_role'] = $_POST['role'];
       }
       if($_POST['join_time']!=''){
           $where['team_member_join_time'] = array('EGT',$_POST['join_time']);
       }
       $where['team_id'] = session('loginSession')['team_id'];

       $where['team_member_remove'] = 2;
       $res = Db::table('up_team_members')->alias('a')
           ->where($where)
           ->join('up_u_user u','u.user_id=a.team_member_user_id','left')
           ->join('up_u_user uuu','uuu.user_id=a.team_member_up_user','left')
           ->field('u.user_username,u.user_phone,uuu.user_username as up_user,a.team_member_role,a.team_member_join_time')
           ->order('a.team_member_join_time desc')
           ->select();
       $xlsCell  = array(
           array('user_username','昵称'),
           array('user_phone','手机号码'),
           array('up_user','所属客户'),
           array('team_member_role','角色'),
           array('team_member_join_time','加入时间')
       );
       $data = $this->exportExcel(session('loginSession')['team_id'],$xlsCell,$res);
       return $data;
   }

    /**
     * 添加成员页面
     */
   public function addMember(){
       $uid = session('loginSession')['user_id'];
       $whereU['user_id_u'] =$uid;
       $whereU['friends_type'] =2;
       $user_id_f = Db::table('up_u_friends')->where('user_id_u',$uid)->column('user_id_f');
       $where['team_id'] = session('loginSession')['team_id'];//团队ID;
       $where['team_member_remove'] = 2;
       $user_id = Db::table('up_team_members')->where($where)->column('team_member_user_id');
       foreach ($user_id_f as $key=>$vo){
            if(in_array($vo,$user_id)){
                unset($user_id_f[$key]);
            }
       }
       $whereMap = '';
       if(count($user_id_f)>0){
           $whereMap['user_id'] = array('in',$user_id_f);
       }
       $user_data = Db::table('up_u_user')->where($whereMap)->field('user_id,user_username,user_phone')->select();
       $this->assign('user_data',$user_data);
       return $this->fetch("member/addMember");
   }

    /**
     * @return string添加团队成员
     */
   public function addTeamMember(){
       $user = input('user/a');
       if(count($user)<=0){
           $returnData['status'] = 0;
           $returnData['msg'] ="选择的人员不能为空";
           return json_encode($returnData);
       }else{
           Db::startTrans();//开启事物

           $user_string =implode(',',$user);
           $data_team['str'] = $user_string;
           $data_team['groupId'] = session('loginSession')['team_id'];//团队ID;
           $data_team['groupName'] = session('loginSession')['team_name'];
           $url = 'http://cjtdapi.xuanwumobile.com/team/addPhpTeam.do';//TODO 缺少url连接地址
           $msg = json_decode($this->httpPost($url,$data_team),true);

           if ($msg['msg']==200) {
               $array = array();
               foreach ($user as $key=>$vo){
                    $data['team_member_id'] = $this->getRandChar(32);
                    $data['team_id'] =session('loginSession')['team_id'];//团队ID
                    $data['team_member_user_id']= $vo;
                    $data['team_member_role']= 3;
                    $data['team_member_join_time']= date('Y-m-d H:i:s');
                   $array[] =$data;
               }
               $res = Db::table('up_team_members')->insertAll($array);
               if($res){
                   Db::commit();//提交事物
                   return json_encode(array("status" => 1, "msg" => "团队成员添加成功！"));
               }else{
                   Db::rollback();//回滚
                   return json_encode(array("status" => 0, "msg" => "团队成员添加失败！"));
               }
           } else {
               Db::rollback();//回滚

               return json_encode(array("status" => 0, "msg" => "团队成员添加失败！"));
           }
       }
   }

   /**
    * 成员导入页面
    */
   public function ImportUser(){

    return $this->fetch('member/ImportUser');
   }

   /**
    * 导入功能
    */
   public function insertImportUser(){
       set_time_limit(0);

       $file_name = $_FILES['excelFile']['name'];//上传的文件名字
        $file_path = $_FILES['excelFile']['tmp_name'];//上传的临时路径
        $file_types = explode('.',$file_name);//切割上传文件名字
        $file_type = $file_types [count ( $file_types ) - 1];//上传的名字后缀

//       vendor("phpoffice.phpexcel.Classes.PHPExcel");
       vendor("phpoffice.phpexcel.Classes.PHPExcel.IOFactory");
       if( $file_type == 'xls' ){
           $inputFileType = 'Excel5';    //这个是读 xls的
       }else{
           $inputFileType = 'Excel2007';//这个是计xlsx的
       }
       $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
       $objPHPExcel = $objReader->load($file_path);

       $objWorksheet = $objPHPExcel->getActiveSheet();

       $highestRow = $objWorksheet->getHighestRow();
       $data = array();//放用户ID的数组
       Db::startTrans();//开启事物
       for ($i=2;$i<=$highestRow;$i++){
           $a = $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();//获取A列的值 手机号码
           $b = $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();//获取B列的值  姓名
           $c = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();//获取C列的值  职务
           $d = $objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();//获取D列的值  角色
           $e = $objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue();//获取E列的值  客户
           $user = $this->selectUserTable($a);//先查询这个人是否已经注册
           if($user['user_id']!=''){//注册了
               $where['team_id'] = session('loginSession')['team_id'];
               $where['team_member_user_id'] = $user['user_id'];
               $filed = 'team_member_id';
               $up_team_members = $this->selectTeamTable($where,$filed);//查询这个人是否存在这个团队里面
               if($up_team_members['team_member_id']==''){//证明这个人不在团队成员里面
                   if($d==4){//证明是客户
                       //判断所属客户的这个用户是否存在
                       $user_kh =$this->selectUserTable($e);
                       if($user_kh['user_id']!=''){//这个人已经注册
                           $whereMap['team_id'] = session('loginSession')['team_id'];
                           $whereMap['team_member_user_id'] = $user_kh['user_id'];
                           $field = 'team_member_id';
                           //查询这个人是否存在这个团队里面
                           $new_team_member = $user_kh['user_id']; //所属客户人的ID
                           $new_up_team_members = $this->selectTeamTable($whereMap,$field);
                           if($new_up_team_members['team_member_id']==''){
                               $this->addTeam($user_kh,1,3);
                               $data[] = $user_kh['user_id'];
                           }
                       }else{//这个没有注册,就证明不存在这个团队里面

                           //插入到用户表
                           $new_result_kh['user_id'] = $this->getRandChar(32);
                           $new_result_kh['user_phone'] = $e;
                           $new_result_kh['user_username'] = $e;
                           Db::table('up_u_user')->insert($new_result_kh);
                           $this->addTeam($new_result_kh,1,3);
                           $new_team_member = $new_result_kh['user_id'];//所属客户人的ID
                           $data[] = $new_result_kh['user_id'];
                       }
                       $this->addTeam($user,session('loginSession')['team_id'],$d,$new_team_member);
                   }else{
                       $this->addTeam($user,session('loginSession')['team_id'],$d);
                   }

                   $data[] = $user['user_id'];//存放用户ID的数组
               }
           }else{//没有注册
               $new_user_null['user_id'] = $this->getRandChar(32);
               $new_user_null['user_phone'] = $a;
               $new_user_null['user_username'] = $a;
               $new_user_null['real_name'] = $b;
               $new_user_null['user_post'] = $c;
               Db::table('up_u_user')->insert($new_user_null);
               if($d==4){
                   $user_kh =$this->selectUserTable($e);
                   if($user_kh['user_id']!='') {//这个人已经注册
                       $whereMap['team_id'] = session('loginSession')['team_id'];//团队ID
                       $whereMap['team_member_user_id'] = $user_kh['user_id'];
                       $field = 'team_member_id';
                       //查询这个人是否存在这个团队里面
                       $new_team_member = $user_kh['user_id']; //所属客户人的ID
                       $new_up_team_members = $this->selectTeamTable($whereMap, $field);
                       if ($new_up_team_members['team_member_id'] == '') {
                           $this->addTeam($user_kh,session('loginSession')['team_id'], 3);
                           $data[] = $user_kh['user_id'];
                       }
                   }else{
                       $new_result_kh['user_id'] = $this->getRandChar(32);
                       $new_result_kh['user_phone'] = $e;
                       $new_result_kh['user_username'] = $e;
                       Db::table('up_u_user')->insert($new_result_kh);
                       $this->addTeam($new_result_kh,1,3);
                       $new_team_member = $new_result_kh['user_id'];//所属客户人的ID
                       $data[] = $new_result_kh['user_id'];
                   }
                   $this->addTeam($new_user_null,session('loginSession')['team_id'],$d,$new_team_member);
               }else{
                   $this->addTeam($new_user_null,session('loginSession')['team_id'],$d);

               }
               $data[] = $new_user_null['user_id'];

           }
       }

       if(count($data)>0){
           $user_string =implode(',',$data);
           $data_res['str'] = $user_string;
           $data_res['groupId'] = session('loginSession')['team_id'];//团队ID;
           $data_res['groupName'] = session('loginSession')['team_name'];
           $url = 'http://cjtdapi.xuanwumobile.com/team/addPhpTeam.do';//TODO 缺少url连接地址
           $msg = json_decode($this->httpPost($url,$data_res),true);
           if ($msg['msg']==200) {
               Db::commit();//提交事物

               return json_encode(array("status" => 1, "msg" => "团队成员添加成功！"));
           }else{
               Db::rollback();//回滚

               return json_encode(array("status" => 0, "msg" => "团队成员添加失败！"));
           }
       }else{
           Db::rollback();//回滚

           return json_encode(array("status" => 0, "msg" => "团队成员添加失败！"));

       }
   }


    /***
     * @param $where
     * @param $field
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     * 查询团队是否存在这个人
     */
    public function selectTeamTable($where,$field){
        $up_team_members = Db::table('up_team_members')->where($where)->field($field)->find();
        return $up_team_members;
    }

    /***
     * @param $where
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     * 查询这个人是否已经存在
     */
    public function selectUserTable($where){
        $user = Db::table('up_u_user')->where('user_phone',$where)->field('user_id')->find();//先查询这个人是否已经注册
        return $user;
    }

    public function addTeam($user_kh,$team_id,$role,$user=''){
        //插入到团队成员表的数据
        $new_team_s['team_member_id'] =$this->getRandChar(32);
        $new_team_s['team_id'] =$team_id;
        $new_team_s['team_member_user_id'] =$user_kh['user_id'];
        $new_team_s['team_member_role'] =$role;
        $new_team_s['team_member_join_time'] = date('Y-m-d H:i:s');
        if($user!=''){
            $new_team['team_member_up_user'] = $user;//客户所属人的ID

        }
        //插入到团队成员表中
        $res = Db::table('up_team_members')->insert($new_team_s);

        return $res;
    }
}